
# 定义一个类BasePage，作为所有页面类的基类
# - 对webdriver常用操作的二次封装
# - 对webelement对象的二次封装
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait as WD
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException,ElementClickInterceptedException


class BasePage(object):
    def __init__(self,driver,url=None):
        self.driver = driver
        if url is not None:
            driver.get(url)
    # 添加显式等待
    def find_element(self,locator):
        return Element(WD(self.driver,10).until(EC.presence_of_element_located(locator=locator)),self.driver)

    def find_elements(self,locator):
        elements = WD(self.driver,10).until(EC.presence_of_all_elements_located(locator=locator))
        return [Element(items,self.driver) for items in elements]

class Element(object):
    def __init__(self,_element,_driver):
        self._element = _element
        self._driver = _driver

    def click(self):
        ignored_exceptions = StaleElementReferenceException,ElementClickInterceptedException
        WD(self._driver,10,ignored_exceptions=ignored_exceptions).until(
            lambda d:not self._element.click()
        )

    def send_keys(self,value):
        WD(self._driver,10).until(
            lambda d:not self._element.send_keys(value)
        )
    #
    # def text(self):
    #     WD(self._driver,10).until(
    #         lambda d:not self._element.text
    #     )

    def text(self, until_not_null=False):
        if not until_not_null:
            return self._element.text
        else:
            waiter = WD(driver=self._driver, timeout=10)

            def wait_not_null(element):
                def _method(d):
                    return self._element.text

                return _method

            return waiter.until(wait_not_null(self))